package Study;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
class Base32 {
    private static final String base32Chars =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
    private static final int[] base32Lookup = {

            0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // '0', '1', '2', '3', '4', '5', '6', '7'

            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // '8', '9', ':', ';', '<', '=', '>', '?'

            0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G'

            0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'

            0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W'

            0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_'

            0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g'

            0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'

            0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w'

            0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL'

    };
    public static String encode(

            final byte[] bytes) {

        int i = 0, index = 0, digit = 0;

        int currByte, nextByte;

        StringBuffer base32 = new StringBuffer((bytes.length + 7) * 8 / 5);
        while (i < bytes.length) {

            currByte = (bytes[i] >= 0) ? bytes[i] : (bytes[i] + 256); // unsign




            /* Is the current digit going to span a byte boundary? */

            if (index > 3) {

                if ((i + 1) < bytes.length) {

                    nextByte = (bytes[i + 1] >= 0) ? bytes[i + 1] : (bytes[i + 1] + 256);

                } else {

                    nextByte = 0;

                }
                digit = currByte & (0xFF >> index);

                index = (index + 5) % 8;

                digit <<= index;

                digit |= nextByte >> (8 - index);

                i++;

            } else {

                digit = (currByte >> (8 - (index + 5))) & 0x1F;

                index = (index + 5) % 8;

                if (index == 0) {

                    i++;

                }

            }

            base32.append(base32Chars.charAt(digit));

        }




        return base32.toString();

    }

    public static byte[] decode(

            final String base32) {

        int i, index, lookup, offset, digit;

        byte[] bytes = new byte[base32.length() * 5 / 8];




        for (i = 0, index = 0, offset = 0; i < base32.length(); i++) {

            lookup = base32.charAt(i) - '0';




            /* Skip chars outside the lookup table */

            if (lookup < 0 || lookup >= base32Lookup.length) {

                continue;

            }




            digit = base32Lookup[lookup];




            /* If this digit is not in the table, ignore it */

            if (digit == 0xFF) {

                continue;

            }




            if (index <= 3) {

                index = (index + 5) % 8;

                if (index == 0) {

                    bytes[offset] |= digit;

                    offset++;

                    if (offset >= bytes.length) {

                        break;

                    }

                } else {

                    bytes[offset] |= digit << (8 - index);

                }

            } else {

                index = (index + 5) % 8;

                bytes[offset] |= (digit >>> index);

                offset++;




                if (offset >= bytes.length) {

                    break;

                }

                bytes[offset] |= digit << (8 - index);

            }

        }

        return bytes;

    }

}
public class TOTP {
    /** Interval of time (seconds) between successive changes of this counter's value. */
    private static final long mTimeStep=30;

    /**
     * Earliest time instant (seconds since UNIX epoch) at which this counter assumes the value of
     * {@code 0}.
     */
    private static final long mStartTime=0;
    public static long getValueAtTime(long time) {

        // According to the RFC:
        // T = (Current Unix time - T0) / X, where the default floor function is used.
        //   T  - counter value,
        //   T0 - start time.
        //   X  - time step.

        // It's important to use a floor function instead of simple integer division. For example,
        // assuming a time step of 3:
        // Time since start time: -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6
        // Correct value:         -2 -2 -2 -1 -1 -1  0  0  0  1  1  1  2
        // Simple division / 3:   -2 -1 -1 -1  0  0  0  0  0  1  1  1  2
        //
        // To avoid using Math.floor which requires imprecise floating-point arithmetic, we
        // we compute the value using integer division, but using a different equation for
        // negative and non-negative time since start time.
        long timeSinceStartTime = time - mStartTime;
        if (timeSinceStartTime >= 0) {
            return timeSinceStartTime / mTimeStep;
        } else {
            return (timeSinceStartTime - (mTimeStep - 1)) / mTimeStep;
        }
    }
    private static byte[] decodeKey(String secret) {
        return Base32.decode(secret);
    }

    static String TOTP(String key) throws GeneralSecurityException {
        long otpState =getValueAtTime(System.currentTimeMillis()/1000);
        String secret=key;
        return computePin(secret,otpState,null);
    }
    private static String computePin(String secret, long otpState, byte[] challenge) throws GeneralSecurityException {
        Mac m=Mac.getInstance("HMACSHA1");
        byte[] bytes= decodeKey(secret);
        m.init(new SecretKeySpec(bytes,""));
        PasscodeGenerator pcg=new PasscodeGenerator(m,6);
        return (challenge == null) ?
                pcg.generateResponseCode(otpState) :
                pcg.generateResponseCode(otpState, challenge);
    }
}
class PasscodeGenerator {
    /**
     * Maximum passcode length, in digits. Must be kept in sync with
     * {@link #DIGITS_POWER}.
     */
    private static final int MAX_PASSCODE_LENGTH = 9;

    /** Default decimal passcode length */
    private static final int PASS_CODE_LENGTH = 6;

    /** The number of previous and future intervals to check */
    private static final int ADJACENT_INTERVALS = 1;

    /**
     * Powers of 10 to shorten the pin to the desired number of digits. This
     * prevents invalid OTP generation when Math.pow() is implemented incorrectly
     * (e.g. when 10^6 != 1000000), and matches the reference implementation in
     * RFC 6238. Must be kept in sync with {@link #MAX_PASSCODE_LENGTH}.
     */
    private static final int[] DIGITS_POWER =
            {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};

    private final Signer signer;
    private final int codeLength;

    /**
     * Using an interface to allow us to inject different signature
     * implementations.
     */
    interface Signer {
        /**
         * @param data Preimage to sign, represented as sequence of arbitrary bytes
         * @return Signature as sequence of bytes.
         * @throws GeneralSecurityException
         */
        byte[] sign(byte[] data) throws GeneralSecurityException;
    }

    /**
     * @param mac A {@link Mac} used to generate passcodes
     */
    public PasscodeGenerator(Mac mac) {
        this(mac, PASS_CODE_LENGTH);
    }

    public PasscodeGenerator(Signer signer) {
        this(signer, PASS_CODE_LENGTH);
    }

    /**
     * @param mac A {@link Mac} used to generate passcodes
     * @param passCodeLength The length of the decimal passcode
     */
    public PasscodeGenerator(final Mac mac, int passCodeLength) {
        this(new Signer() {
            @Override
            public byte[] sign(byte[] data){
                return mac.doFinal(data);
            }
        }, passCodeLength);
    }

    public PasscodeGenerator(Signer signer, int passCodeLength) {
        if ((passCodeLength < 0) || (passCodeLength > MAX_PASSCODE_LENGTH)) {
            throw new IllegalArgumentException(
                    "PassCodeLength must be between 1 and " + MAX_PASSCODE_LENGTH + " digits.");
        }
        this.signer = signer;
        this.codeLength = passCodeLength;
    }

    private String padOutput(int value) {
        String result = Integer.toString(value);
        for (int i = result.length(); i < codeLength; i++) {
            result = "0" + result;
        }
        return result;
    }

    /**
     * @param state 8-byte integer value representing internal OTP state.
     * @return A decimal response code
     * @throws GeneralSecurityException If a JCE exception occur
     */
    public String generateResponseCode(long state)
            throws GeneralSecurityException {
        byte[] value = ByteBuffer.allocate(8).putLong(state).array();
        return generateResponseCode(value);
    }


    /**
     * @param state 8-byte integer value representing internal OTP state.
     * @param challenge Optional challenge as array of bytes.
     * @return A decimal response code
     * @throws GeneralSecurityException If a JCE exception occur
     */
    public String generateResponseCode(long state, byte[] challenge)
            throws GeneralSecurityException {
        if (challenge == null) {
            return generateResponseCode(state);
        } else {
            // Allocate space for combination and store.
            byte[] value =
                    ByteBuffer.allocate(8 + challenge.length)
                            .putLong(state) // Write out OTP state
                            .put(challenge, 0, challenge.length) // Concatenate with challenge.
                            .array();
            return generateResponseCode(value);
        }
    }

    /**
     * @param challenge An arbitrary byte array used as a challenge
     * @return A decimal response code
     * @throws GeneralSecurityException If a JCE exception occur
     */
    public String generateResponseCode(byte[] challenge)
            throws GeneralSecurityException {
        byte[] hash = signer.sign(challenge);

        // Dynamically truncate the hash
        // OffsetBits are the low order bits of the last byte of the hash
        int offset = hash[hash.length - 1] & 0xF;
        // Grab a positive integer value starting at the given offset.
        int truncatedHash = hashToInt(hash, offset) & 0x7FFFFFFF;
        int pinValue = truncatedHash % DIGITS_POWER[codeLength];
        return padOutput(pinValue);
    }

    /**
     * Grabs a positive integer value from the input array starting at
     * the given offset.
     * @param bytes the array of bytes
     * @param start the index into the array to start grabbing bytes
     * @return the integer constructed from the four bytes in the array
     */
    private int hashToInt(byte[] bytes, int start) {
        DataInput input = new DataInputStream(
                new ByteArrayInputStream(bytes, start, bytes.length - start));
        int val;
        try {
            val = input.readInt();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        return val;
    }

    /**
     * @param challenge A challenge to check a response against
     * @param response A response to verify
     * @return True if the response is valid
     */
    public boolean verifyResponseCode(long challenge, String response)
            throws GeneralSecurityException {
        String expectedResponse = generateResponseCode(challenge, null);
        return expectedResponse.equals(response);
    }

    /**
     * Verify a timeout code. The timeout code will be valid for a time
     * determined by the interval period and the number of adjacent intervals
     * checked.
     *
     * @param timeoutCode The timeout code
     * @return True if the timeout code is valid
     */
    public boolean verifyTimeoutCode(long currentInterval, String timeoutCode)
            throws GeneralSecurityException {
        return verifyTimeoutCode(timeoutCode, currentInterval,
                ADJACENT_INTERVALS, ADJACENT_INTERVALS);
    }

    /**
     * Verify a timeout code. The timeout code will be valid for a time
     * determined by the interval period and the number of adjacent intervals
     * checked.
     *
     * @param timeoutCode The timeout code
     * @param pastIntervals The number of past intervals to check
     * @param futureIntervals The number of future intervals to check
     * @return True if the timeout code is valid
     */
    public boolean verifyTimeoutCode(String timeoutCode,
                                     long currentInterval,
                                     int pastIntervals,
                                     int futureIntervals) throws GeneralSecurityException {
        // Ensure that look-ahead and look-back counts are not negative.
        pastIntervals = Math.max(pastIntervals, 0);
        futureIntervals = Math.max(futureIntervals, 0);

        // Try upto "pastIntervals" before current time, and upto "futureIntervals" after.
        for (int i = -pastIntervals; i <= futureIntervals; ++i) {
            String candidate = generateResponseCode(currentInterval - i, null);
            if (candidate.equals(timeoutCode)) {
                return true;
            }
        }

        return false;
    }
}